<template>
  <div class="menu-management">
    <!-- 顶部操作区 -->
    <div class="operation-bar">
      <el-button type="primary"  @click="handleAddLevel1">
        添加菜单
      </el-button>
    </div>

    <!-- 菜单表格 -->
    <el-table
      :data="menuList"
      :row-key="(row) => row.id"
      border
      style="width: 100%; margin-top: 20px"
      :tree-props="{ children: 'children', indent: 0 }"  
      :header-cell-style="tableHeaderStyle"
      :row-class-name="tableRowClassName"
      ref="menuTable"
    >
      <!-- 菜单名称列 - 核心改造区域 -->
      <el-table-column prop="name" label="菜单名称" min-width="180">
        <template #default="scope">
          <div class="menu-name">
                  <span v-html="`${'&nbsp;'.repeat(scope.row.level * 8)}${scope.row.name}`"></span>

          </div>
        </template>
      </el-table-column>

      <!-- 图标列 -->
      <el-table-column prop="css" label="css" width="190"></el-table-column>

      <!-- 路径列 -->
      <el-table-column
        prop="url"
        label="路径"
        min-width="150"
      ></el-table-column>

      <!-- 排序列 -->
      <el-table-column prop="sort" label="排序" width="80"></el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="400">
        <template #default="scope">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleAddSubMenu(scope.row)"
          >
            添加
          </el-button>

          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>

          <el-button
            type="danger"
            plain
            size="mini"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>

          <!-- <el-button
            :type="scope.row.status ? 'info' : 'success'"
            plain
            size="mini"
            @click="handleToggleStatus(scope.row)"
          >
            {{ scope.row.status ? "禁用" : "启用" }}
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑菜单弹窗 -->
    <el-dialog
      :title="
        form.id ? '编辑菜单' : form.parentId ? '添加子菜单' : '添加菜单'
      "
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="menuForm"
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入菜单名称"
            maxlength="50"
          ></el-input>
        </el-form-item>

        <el-form-item label="css" prop="css">
          <el-input
            v-model="form.css"
            placeholder="例如：el-icon-home"
            maxlength="50"
          ></el-input>
        </el-form-item>

        <el-form-item label="路径" prop="url">
          <el-input
            v-model="form.url"
            placeholder="请输入路径"
            maxlength="100"
          ></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input
            v-model.number="form.sort"
            placeholder="请输入排序号"
            type="number"
            min="0"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "MenuManagement",
  data() {
    return {
      loading: false,
      // 菜单列表数据
      menuList: [],

      // 弹窗显示状态
      dialogVisible: false,

      // 表单数据
      form: {
        id: null,
        name: "",
        css: "",
        url: "",
        sort: 0,
        parentId: null,
      },

      // 表单验证规则
      formRules: {
        name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],

        url: [{ required: true, message: "请输入路径", trigger: "blur" }],
        sort: [
          { required: true, message: "请输入排序号", trigger: "blur" },
          { type: "number", message: "请输入有效的数字", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    tableHeaderStyle() {
      return {
        "background-color": "#f8f9fa",
        color: "#495057",
        "font-weight": "500",
      };
    },
  },
  created() {
    this.fetchMenuList();
  },
  methods: {
      addLevelToMenus(menus, level) {
      return menus.map(menu => {
        // 给当前菜单添加 level 属性（一级0，二级1，三级2...）
        const newMenu = { ...menu, level };
        // 如果有子菜单，递归添加 level（子菜单层级+1）
        if (menu.children && menu.children.length > 0) {
          newMenu.children = this.addLevelToMenus(menu.children, level + 1);
        }
        return newMenu;
      });
    },

    // 修改：获取菜单数据后，调用 addLevelToMenus 添加层级
    async fetchMenuList() {
      try {
        const res = await this.$request.get("/system/sysMenu/all");
        if (res.code === 200) {
          // 1. 先给原始数据添加 level 属性
          this.menuList = this.addLevelToMenus(res.data || [], 0);
          
          // 2. 修复 toggleRowExpansion 报错（先判断 ref 存在）
          this.$nextTick(() => {
            if (this.$refs.menuTable) {
              this.menuList.forEach((row) => {
                if (row.children && row.children.length > 0) {
                  this.$refs.menuTable.toggleRowExpansion(row, true);
                }
              });
            }
          });
        }
      } catch (error) {
        console.error("获取菜单表格数据失败:", error);
        this.$message.error("获取菜单数据失败，请重试");
      }
    },

    tableRowClassName({ row, rowIndex }) {
      return rowIndex % 2 === 1 ? "table-row-even" : "";
    },

    handleAddLevel1() {
      this.resetForm();
      this.form.parentId = null;
      this.dialogVisible = true;
    },
 handleEdit(row) {
    // 将选中行的菜单数据深拷贝到 form 中（避免直接修改原数据）
    this.form = { ...row }; 
    // 打开弹窗（弹窗标题会根据 form.id 自动显示为“编辑菜单”）
    this.dialogVisible = true;
  },
    handleAddSubMenu(parentRow) {
      this.resetForm();
      this.form.parentId = parentRow.id;
      this.form.sort = (parentRow.children && parentRow.children.length || 0) + 1;
      this.dialogVisible = true;
    },

    // 修改：保存菜单后，重新添加层级（确保新增/编辑的菜单有 level）
    handleSave() {
  this.$refs.menuForm.validate(async (valid) => {
    if (valid) {
      // 1. 准备请求参数：包含 parentId 和所有表单信息
      // 过滤掉不需要传给后端的字段（如临时 id，若后端自动生成 id）
      const requestData = {
        parentId: this.form.parentId, // 父菜单ID（新增子菜单时存在，一级菜单为 null/undefined）
        name: this.form.name,         // 菜单名称
        css: this.form.css,           // 图标CSS
        url: this.form.url,           // 路径
        sort: this.form.sort          // 排序
      };

      try {
        // 2. 区分“新增”和“编辑”，调用不同后端接口
        if (this.form.id) {
          // 👉 编辑场景：调用后端 update 接口（若有），携带 id 和表单数据
          await this.$request.put(`/system/sysMenu/update`, {
            id: this.form.id, // 菜单ID（必传，用于后端定位要修改的菜单）
            ...requestData    // 其他表单字段
          });
          this.$message.success("菜单编辑成功");
        } else {
          // 👉 新增场景：调用后端 add 接口，携带 parentId 和表单数据
          await this.$request.post(`/system/sysMenu/add`, requestData);
          this.$message.success("菜单添加成功");
        }

        // 3. 接口成功后：重新拉取菜单列表（保证数据和后端同步）
        await this.fetchMenuList();
        // 4. 关闭弹窗
        this.dialogVisible = false;

      } catch (error) {
        // 5. 接口失败：提示错误信息
        console.error("菜单保存失败:", error);
        this.$message.error("菜单保存失败，请重试");
      }
    }
  });
},

    // 修改：删除菜单后，重新添加层级（确保剩余菜单 level 正确）
    handleDelete(row) {
  this.$confirm(
    `确定要删除【${row.name}】吗？${row.children && row.children.length > 0 ? '该菜单包含子菜单，删除后子菜单也会一并删除' : ''}`, 
    "确认删除", 
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: false // 普通文本提示，无需HTML
    }
  )
    .then(async () => { // 改为 async 函数，方便内部 await 调用接口
      try {
        // 1. 调用后端 delete 接口（传递菜单ID，后端根据ID删除）
        // 接口地址示例：/system/sysMenu/delete/{id}（请与后端接口地址保持一致）
        await this.$request.delete(`/system/sysMenu/delete/${row.id}`);
        
        // 2. 接口成功后：重新拉取菜单列表（确保前端数据与后端同步）
        await this.fetchMenuList();
        
        // 3. 提示删除成功
        this.$message.success("菜单已删除");

      } catch (error) {
        // 4. 接口失败：提示错误信息
        console.error("菜单删除失败:", error);
        this.$message.error("菜单删除失败，请重试");
      }
    })
    .catch(() => {
      // 5. 用户取消删除：提示信息
      this.$message.info("已取消删除");
    });
},

    // 以下 updateMenu、addSubMenu、deleteSubMenu、handleToggleStatus、resetForm 方法保持不变
    updateMenu(menuList, updatedMenu) {
      for (let i = 0; i < menuList.length; i++) {
        if (menuList[i].id === updatedMenu.id) {
          menuList[i] = { ...updatedMenu };
          return true;
        }
        if (menuList[i].children && menuList[i].children.length > 0) {
          const found = this.updateMenu(menuList[i].children, updatedMenu);
          if (found) return true;
        }
      }
      return false;
    },

    addSubMenu(menuList, subMenu) {
      for (let i = 0; i < menuList.length; i++) {
        if (menuList[i].id === subMenu.parentId) {
          if (!menuList[i].children) {
            menuList[i].children = [];
          }
          menuList[i].children.push(subMenu);
          return true;
        }
        if (menuList[i].children && menuList[i].children.length > 0) {
          const found = this.addSubMenu(menuList[i].children, subMenu);
          if (found) return true;
        }
      }
      return false;
    },

    deleteSubMenu(menuList, row) {
      for (let i = 0; i < menuList.length; i++) {
        if (menuList[i].children && menuList[i].children.length > 0) {
          const childIndex = menuList[i].children.findIndex(
            (item) => item.id === row.id
          );
          if (childIndex !== -1) {
            menuList[i].children.splice(childIndex, 1);
            return true;
          }
          const found = this.deleteSubMenu(menuList[i].children, row);
          if (found) return true;
        }
      }
      return false;
    },

    handleToggleStatus(row) {
      row.status = !row.status;
      this.$message.success(`菜单已${row.status ? "启用" : "禁用"}`);
    },

    resetForm() {
      this.form = {
        id: null,
        name: "",
        css: "",
        url: "",
        sort: 0,
        parentId: null,
      };
      if (this.$refs.menuForm) {
        this.$refs.menuForm.resetFields();
      }
    },
  },
};
</script>

<style scoped>
/* 核心样式：调整箭头位置到最前面 */
::v-deep .el-table .el-table__expand-icon {
  position: absolute;
  left: 10px;  /* 固定在最左侧 */
  margin: 0 !important;
}

/* 菜单名称列容器样式，给箭头留出位置 */
::v-deep .el-table td:first-child {
  position: relative;
  padding-left: 30px !important;  /* 给箭头留出空间 */
}

::v-deep .el-table {
  border: none !important;
}

::v-deep .el-table th,
::v-deep .el-table td {
  border: none !important;
}

.menu-management {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.operation-bar {
  margin-bottom: 15px;
}

.menu-name {
  display: flex;
  align-items: center;
}

.status-enabled {
  color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-disabled {
  color: #909399;
  background-color: rgba(144, 147, 153, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

::v-deep .el-table {
  border: 1px solid #ebeef5;
}

::v-deep .el-table th {
  border-bottom: 1px solid #ebeef5;
}

::v-deep .el-table td {
  border-bottom: 1px solid #ebeef5;
}

::v-deep .table-row-even {
  background-color: #f8f9fa;
}

::v-deep .el-button--mini {
  margin-right: 5px;
}
</style>
